#!/bin/bash
##--此脚本用于使用rman工具在异机做数据备份迁移还原
##--需在root帐号下执行此脚本

echo "use rman to backup oracle"
restoredir=/home/rman_backup/data/20220103203234
echo "restoredir=$restoredir"
chmod -R 755 $restoredir
chown -R oracle:oinstall $restoredir

ORACLE_SID=ORCL
ORACLE_BASE=/u01/app/oracle
ORACLE_HOME=$ORACLE_BASE/product/21.0.0/dbhome_1
ORA_INVENTORY=/u01/app/oraInventory
DATA_DIR=/u02/oradata
ADUMP_DIR=$ORACLE_BASE/admin/$ORACLE_SID/adump
echo "ORACLE_BASE=$ORACLE_BASE"
echo "ORACLE_HOME=$ORACLE_HOME"
echo "ORA_INVENTORY=$ORA_INVENTORY"
echo "DATA_DIR=$DATA_DIR"
echo "ADUMP_DIR=$ADUMP_DIR"

if [ ! -d $ORACLE_HOME ]; then
mkdir -p $ORACLE_HOME
else
echo "dir $ORACLE_HOME already exist"
fi

chown -R oracle:oinstall $ORACLE_BASE
chmod -R 775 $ORACLE_BASE
chown -R oracle:oinstall $ORACLE_HOME
chmod -R 775 $ORACLE_HOME

if [ ! -d $ORA_INVENTORY ]; then
echo "mkdir -p $ORA_INVENTORY"
mkdir -p $ORA_INVENTORY
else
echo "dir $ORA_INVENTORY already exist"
fi
chown -R oracle:oinstall $ORA_INVENTORY
chmod -R 775 $ORA_INVENTORY

if [ ! -d $ADUMP_DIR ]; then
echo "mkdir -p $ADUMP_DIR"
mkdir -p $ADUMP_DIR
else
echo "dir $ADUMP_DIR already exist"
fi
chown -R oracle:oinstall $ADUMP_DIR
chmod -R 775 $ADUMP_DIR

if [ ! -d $DATA_DIR ]; then
echo "mkdir -p $DATA_DIR"
mkdir -p $DATA_DIR
else
echo "dir $DATA_DIR already exist"
fi
chown -R oracle:oinstall $DATA_DIR
chmod -R 775 $DATA_DIR

RMAN_FILE=$restoredir/rman-restore.log

mkdir -p $ORACLE_BASE/dbs/ 
cat > $ORACLE_BASE/dbs/initORCL.ora <<EOF
db_name=ORCL
EOF
chown -R oracle:oinstall $ORACLE_BASE/dbs/initORCL.ora
chmod -R 775 $ORACLE_BASE/dbs/initORCL.ora

chown root:root $ORACLE_HOME/bin/oradism
chmod 4750 $ORACLE_HOME/bin/oradism

#rman执行还原命令
su - oracle -c "
rman log=${RMAN_FILE} <<\EOF
connect target /

run {
startup nomount;

restore spfile from '$restoredir/spfile.bak';
create pfile from spfile;

startup nomount force pfile='$ORACLE_BASE/dbs/initORCL.ora';
restore controlfile from '$restoredir/controlfile.bak';

alter database mount;
restore database;       

recover database;
}
exit;
EOF
"

#打开数据库
su - oracle -c "sqlplus / as sysdba <<\EOF
SELECT OPEN_MODE from v\$database;
alter database open resetlogs;
SELECT OPEN_MODE from v\$database;
exit;
EOF
"
#检查数据写入
su - oracle -c "sqlplus C##qms/windows-999 <<EOF
select MAX(CRON_DATE) from TST_CRONTB;
exit;
EOF
"

echo "cat ${RMAN_FILE}"
ls -l $restoredir/*
#其他参考命令
:<<!
su - oracle -c 'rlwrap sqlplus C##qms/windows-999'
su - oracle -c 'rlwrap rman target /'

su - oracle -c "dbca -silent -deleteDatabase -sourcedb ORCL -sid ORCL -sysDBAUserName SYS -sysDBAPassword Windows-789"

!